require 'net/http'
require 'net/https'
require 'uri'

module Provider

  class SwisscomCH< AbstractProvider

    @sms_sender

    @login_name
    @password

    def initialize(sms_sender)
      @sms_sender = sms_sender
      @login_name = @sms_sender.get_main.login_name
      @password = @sms_sender.get_main.password
    end

    def send(to, text)
      @host = 'www.swisscom-mobile.ch'
      @port = 443
      @sms_path = '/youth/sms_senden-de.aspx'

      @http = Net::HTTP.new(@host, @port)
      @http.use_ssl = true
      @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      path = '/youth/sms_senden-de.aspx?login'

      # GET request -> so the host can set his cookies
      resp, data = @http.get(path, nil)
      @cookie = resp.response['set-cookie']
      #puts "cookies received: #{resp.response['set-cookie']}"

      # POST request -> logging in
      data = "isiwebappid=mobile&isiwebargs=login&isiwebjavascript=no&isiwebmethod=authenticate&isiweburi=/youth/sms_senden-de.aspx?login&isiwebuserid=#{@login_name}&isiwebpasswd=#{@password}"
      headers = standard_headers

      resp, data = @http.post(path, data, headers)
      #puts "cookies received: #{resp.response['set-cookie']}"
      @cookie = resp.response['set-cookie']

      if resp.code == "200"
        #raise "Login failed. Wrong username or password?"
        self.sms_not_sent("Wrong login or password?")
      else
        # send sms
        data = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE_SCM=5&__VIEWSTATE=&CobYouthSMSSenden:txtMessage=#{text}&CobYouthSMSSenden:txtNewReceiver=#{to}&CobYouthSMSSenden:btnSend=Senden&FooterControl:hidNavigationName=SMS senden&FooterControl:hidMailToFriendUrl=youth/sms_senden-de.aspx"
        resp, data = @http.post(@sms_path, data, standard_headers)

        # log out
        path = '/youth/youth_zone_home-de.aspx?logout'
        resp, data = @http.get(path, standard_headers)
      end
    end

    def	standard_headers(referer="")
      return {
        'Cookie' => @cookie,
        'Referer' => referer,
        'Content-Type' => 'application/x-www-form-urlencoded'
      }
    end

    def sms_left
      #http = Net::HTTP.new('www.swisscom-mobile.ch', 443)
      #http.use_ssl = true
      #http.verify_mode = OpenSSL::SSL::VERIFY_NONE

      path = '/youth/sms_senden-de.aspx'

      resp, data = @http.get(path, standard_headers)
      #puts resp.body
      @sms_left = resp.body.scan(/<span id="CobYouthMMSSMSKonto_lblGuthaben">(.+)<\/span>/)
      return @sms_left[0][0]
    end

  end

end
